<template>
  <view>
    <topBackGroundS :backisShow1="1" :banner1="2" :fixed="fixed"></topBackGroundS>
    <view id="container" class="container" :style="[{'overflow': (isSlide?'hidden':'')},{'height': (isSlide?windowHeight:'auto')}]" >
      <view class="pen_content">
        <!-- 无任何绑定设备 -->
        <view v-if="!isBind">
          <view class="pen_item">
            <view class="penItem_center">
              <text class="pen_text">无任何绑定设备</text>
            </view>
            <button @click="addPenFn" class="connect_btn"> + 添加</button>
          </view>
        </view>

        <!-- 有绑定设备 -->
        <penListTab v-if="isBind" :penData="currentPen" :btnName="'切换'" @tabpen="tabPen"></penListTab>
      
        <!-- 有作品 -->
        <view  v-if="isHaveOffering">
          <view class="refresh">
            <text>下拉刷新</text>
            <image style="width: 14px; height: 14px; margin-left: 4px;" src="../../images/arrow_down.png" />
          </view>

          <view class="offering_list">
            <view class="offe_item" v-for="(item,index) in offList" :key="index" @click="toDetail(item.url)">
              <image style="width: 100%; height: 100%;" :src="item.url" />
              <text class="cheack_detal">查看详情</text>
            </view>
          </view>

          <view v-show="isLoading" class="loading_box">
            <image class="icon_loading" src="../../images/icon_loading.png"/> <text class="loading_text">加载中...</text>
          </view>
          <view v-show="isNoMore" class="no_more_box">
            <text class="no_more"> - 没有更多了 - </text>
          </view>
          
        </view>

        <!-- 暂无作品 -->
        <view v-if="!isHaveOffering" class="no_offering_content">
          <image class="no_offering" src="../../images/no_offering.png" />
          <text class="no_offering_text">暂无作品</text>
        </view>
      </view>
    </view>

    <!-- 底部滑出层 -->
    <view v-show="isSlide" class="black_bg"></view>
    <view class="slide_view" id="slide_view" :style="[{'position':(isSlide?'absolute':'fixed')},{'bottom': (!isSlide?slideHeight:'0')}]">
      <view class="close_btn" @click="closeSlide"></view>
      <text class="slide_title">选择设备</text>

      <view class="choose_list">
        <penListChoose :penData="penList" :dindex="currentInListIndex" @clickPen="choosePen"></penListChoose>
      </view>

      <view class="slide_bottom">
        <button class="bind_new_device" plain="true" @click="addPenFn">绑定新设备</button>
        <button @click="confirmChoose">确认</button>
      </view>
    </view>
    
    

    <!-- 图片预览以及下载 -->
    <view v-show="clickPic" class="preview-container" @click="closeDetailPic">
      <view class="mark"></view>
      <view class="image-wrapper">
        <image
          :src="imageUrl"
          class="preview-image"
          mode="aspectFit"
        />
      </view>
      <button class="download-button" @click.stop="clickDownLoad">
        <image class="download_icon" src="../../images/icon_download_pic.png" />
        下载作品
      </button>
      <view class="mark"></view>
    </view>
    <!-- <button style="position: absolute; z-index: 100000;" @click="addDevice()">添加设备</button> -->
  </view>
</template>
    
<script setup>
  import Taro from '@tarojs/taro';
  import {onunload} from '@tarojs/taro';
  import penListTab from '../../components/penListTab.vue'
  import penListChoose from '../../components/penlistchoose.vue'
  import topBackGroundS from '../../../src/components/backGroundS.vue'
  import config from '../../network/baseUrl'
  import { ref, reactive, onMounted, watch, onBeforeMount } from 'vue'
  import requset from '../../network/request'
  import { getCurrentInstance } from 'vue';
  import { useBluetoothStore } from '../../store/blueTooth'
import { Toast } from '@nutui/nutui-taro';

  const { 
    state, 
    buildWifiFrame,
    sendWifiFrameToModule,
    writeBLECharacteristicValue,
    getDeviceStatus,
    string2buffer,
    ab2hex,
    closeBluetoothAdapter,
    resetState,
    createBLEConnection,
    stopBluetoothDevicesDiscovery,
    openBluetoothAdapter,
    getBLEDeviceServices,
  } = useBluetoothStore()

  const instance = getCurrentInstance();
  instance.appContext.config.globalProperties.$loadFontFace()
  
  const userId = Taro.getStorageSync('userId');
  const userToken = Taro.getStorageSync('token');
  console.log('userId:', userId)
  console.log('userToken:', userToken)

  let isBind = ref(false)           // 是否有笔
  let isHaveOffering = ref(false)   // 有无作品
  let fixed = ref(false)            // 上拉时顶部导航覆盖页面
  let chooseInfo = {}               // 记录选择笔是否与当前笔一致
  let isSlide = ref(false)          // 底部滑出笔列表
  let isLoading = ref(false)        // 作品列表上拉时是否显示Loading
  let isNoMore = ref(false)         // 有无更多作品
  let currentInListIndex = ref(0)   // 当前笔在列表中的序号
  let offList = ref([])             // 设备作品列表

  let clickPic = ref(false)         // 图片预览是否显示
  let imageUrl = ref('')            // 图片预览中图片的url
  let deviceId = ''                 // 存放设备Id
  let currentPen = ref([])          // 当前设备
  const penList = ref([])           // 设备列表
  let slideHeight = ref(-1400+'px') // 初始化底部滑出的位置
  let isTabDevice = false

  // 分页
  let pageNo = 0  
  let total = 0  //25
  const pageSize = 10  //10
  let totalPages = 0
  let isNoData = false


  let connentTimer = null

  const connectDeiveData = reactive({
    nameDeviceId: '',
    snDeviceId: '',
    name:''
  })

  state.isInoffering = true  // 是否在作品页

  Taro.removeStorageSync('lastConnectedDevice')
  const prevDeviceId = Taro.getStorageSync('lastConnectedDevice');
  console.log('getStorageSync:', prevDeviceId )


  
  autoConnectBlueThooth()
  
  function autoConnectBlueThooth() {
    Taro.onBLEConnectionStateChange((res) => {
      if (res.connected) {
        console.log('检测到设备已连接');
        Taro.showToast({
          title: '设备已连接',
          icon: 'none'
        });
        clearInterval(connentTimer); 
      } else {
        console.log('检测到设备已断开连接');
        Taro.showToast({
          title: '设备已断开连接',
          icon: 'none'
        });
        state.sn = ''
        state.electricity = 0
        // 在这里执行设备断开连接后的逻辑，例如提示用户、尝试重新连接等
        if (connectDeiveData.nameDeviceId) {
          
          linkBlueAgain(connectDeiveData.nameDeviceId, connectDeiveData.snDeviceId, connectDeiveData.name)
          connentTimer = setInterval(() => {
            linkBlueAgain(connectDeiveData.nameDeviceId, connectDeiveData.snDeviceId, connectDeiveData.name)
          }, 60000)
        }
      }
    });
  }

  
  watch(()=>currentPen.value, (val) => {
    connectBluethooth(currentPen.value[0].mac, currentPen.value[0].deviceId, currentPen.value[0].nickName)
    console.log('currentPen.value[0].mac:', currentPen.value[0].mac)
    console.log('currentPen.value[0].deviceId:', currentPen.value[0].deviceId)
    console.log('currentPen.value[0].nickName:', currentPen.value[0].nickName)
    connectDeiveData.nameDeviceId = currentPen.value[0].mac
    connectDeiveData.snDeviceId = currentPen.value[0].deviceId
    connectDeiveData.name = currentPen.value[0].nickName
  }, { deep: true })

  
  
  // 获取可视区高度
  let windowHeight = ref(200)
  Taro.getSystemInfo({
    success: function(res) {
      // windowHeight.value = res.screenHeight + 200
      windowHeight.value = '100%'
      console.log('windowHeight::::', res.windowHeight)
      console.log('screenHeight::::', res.screenHeight)
    }
  })
  slideHeight.value = 0 - windowHeight.value+'px'

  // 没有笔，添加笔
  function addPenFn() {
    // const prevDeviceId = Taro.getStorageSync('lastConnectedDevice');
    if (state.lastConnectedDevice ) {
      console.log('state.lastConnectedDevice:', state.lastConnectedDevice)
      Taro.closeBLEConnection({
        deviceId: state.lastConnectedDevice,
        success: function(res) {
          state.connected = false
          console.log('addPenFn - 连接已关闭', res);
        },
        fail: function(res) {
          console.log('addPenFn - 关闭连接失败', res);
        }
      });
    }
    console.log('添加')
    // resetState()
    Taro.navigateTo({
      url: '/pages/bind/index',
    })
  }

  // 连接蓝牙
  function connectBluethooth(nameDeviceId, snDeviceId, name) {

    console.log('nameDeviceId:',nameDeviceId)
    state.isInoffering = true
    console.log('state.lastConnectedDevice:', state.lastConnectedDevice)

    if (state.fromPage === 'linkwifi') {
      console.log('从linkwifi页面跳转过来，什么都不做')
    } else if ( state.lastConnectedDevice ){
      Taro.closeBLEConnection({
        deviceId: state.lastConnectedDevice,
        success: function(res) {
          state.connected = false
          console.log('已连接过设备，连接已关闭', res);
          // disconnectAllBluetoothDevices()
          linkBlueAgain(nameDeviceId, snDeviceId, name) 
        },
        fail: function(res) {
          console.log('关闭连接失败', res);
        }
      });
    }else{
      console.log('没连接过设备')
      // disconnectAllBluetoothDevices()
      linkBlueAgain(nameDeviceId, snDeviceId, name)
    }
  }

  // 去掉冒号
  function removeColons(mac) {
    return mac.replace(/:/g, '');
  }

  // 切换设备重新搜索
  function linkBlueAgain(nameDeviceId, snDeviceId, name) {
    console.log('nameDeviceId-before:', nameDeviceId)
    const newNameDeviceId = removeColons(nameDeviceId) // 去冒号
    console.log('linkBlueAgain-newNameDeviceId:', newNameDeviceId)
    console.log('state::::', state)
    state.devices = [] // 清空搜索列表
    state.sn = ''
    state.electricity = 0

    Taro.closeBluetoothAdapter({
      success (res) {
        openBluetoothAdapter()
      }
    })

    // 监听 蓝牙搜索中的数据，匹配当前设备的名字
    watch(() => state.devices.length, (val) => {

      if( state.isInoffering ) { // 在作品页面 并且在切换的时候
        state.devices.forEach(stateItem => {
          console.log('stateItem:', stateItem)
          console.log('newNameDeviceId:', newNameDeviceId)
          if( stateItem.name.includes(newNameDeviceId)) {
            // 找到该设备
            console.log('匹配到该设备：',stateItem.name)
            stopBluetoothDevicesDiscovery();
            console.log('state.isInoffering:', state.isInoffering)
            if(state.isInoffering) {
              createBLEConnection(stateItem.deviceId, name)
            }
          }
        })
      }
    }, { deep: true })

    setTimeout(() => {
      stopBluetoothDevicesDiscovery();
    },3000)

  }

  // 断开所有蓝牙连接
  async function disconnectAllBluetoothDevices() {
    try {
      // 获取所有已连接的蓝牙设备
      const res = await Taro.getConnectedBluetoothDevices();
      const devices = res.devices;
  
      if (devices.length === 0) {
        console.log('当前没有已连接的蓝牙设备');
        return;
      }
  
      console.log('已连接的蓝牙设备列表:', devices);
  
      // 遍历设备列表，逐个断开连接
      for (const device of devices) {
        const deviceId = device.deviceId;
        try {
          await Taro.closeBLEConnection({ deviceId });
          console.log(`已断开设备: ${deviceId}`);
        } catch (error) {
          console.error(`断开设备 ${deviceId} 时出错:`, error);
        }
      }
  
      console.log('所有蓝牙设备已断开连接');
    } catch (error) {
      console.error('获取已连接的蓝牙设备时出错:', error);
    }
  }

  // 
  function linkBlues(deviceId, snDeviceId, name) {
    console.log('linkBlues-deviceId:', deviceId)
    Taro.openBluetoothAdapter({
      success: (res) => {
        // createBLEConnection(deviceId, obj.name )
        Taro.createBLEConnection({
          deviceId:deviceId,
          success: () => {
            state.connected = true
            state.name = name
            // state.deviceId = deviceId
            state.mac = deviceId
            // Taro.setStorageSync('lastConnectedDevice', deviceId);
            getBLEDeviceServices(deviceId)
          },
          fail:(res) => {
            console.log('创建蓝牙连接失败:', res)
            state.connected = false
            state.index = 2
          }
        })
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          Taro.onBluetoothAdapterStateChange((res) => {
            console.log('打开蓝牙适配器 - openBluetoothAdapter失败中的 onBluetoothAdapterStateChange:', res)
            if (res.available) {
              startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  }


  // 切换毛笔
  function tabPen(obj) {
    console.log('当前设备：：', obj)
    // 当前笔的index
    const index = findIndex(penList.value, obj.deviceId, 'deviceId')
    currentInListIndex.value = -1
    const timer = setTimeout(() => {
      console.log('index::::::::', index)
      currentInListIndex.value = index
      clearTimeout(timer)
    },200)
    Taro.hideTabBar().then(()=>{
      isSlide.value = true;
    })
  }

  // 选择设备
  function choosePen(obj) {
    // console.log(obj)
    chooseInfo = obj
    deviceId = chooseInfo.deviceId
  }

  // 确认选择设备 
  function confirmChoose() {
    console.log(chooseInfo.deviceId !== currentPen.value[0].deviceId)
    if( chooseInfo.deviceId !== currentPen.value[0].deviceId ) {
      currentPen.value[0] = chooseInfo 
      pageNo=0
      offList.value = []
      // isNoMore.value = false
      isNoData = false
      isTabDevice = true
      freshList()
      
    }
    isSlide.value=false
    Taro.showTabBar()
  }

  // 页面滚动时判断顶部导航固定距离
  Taro.usePageScroll((res) => {
    if (res.scrollTop > 50) {
      fixed.value = true
    } else {
      fixed.value = false
    }
  })

  // 点击图片关闭预览
  function closeDetailPic() {
    imageUrl.value = ''
    clickPic.value = false
    Taro.showTabBar()
  }

  // 点击作品弹出预览图
  function toDetail(url) {
    Taro.hideTabBar()
    imageUrl.value = url
    clickPic.value = true
  }

  // 找到设备id在列表中对应的index
  function findIndex(arr, id, str) {
    let index = 0
    for( let i=0; i<arr.length; i++ ) {
      if ( arr[i][str] === id) {
        index = i
      }
    }
    return index
  }

  // 底部滑出笔列表的关闭按钮
  function closeSlide() {
    isSlide.value = false
    setTimeout(() => {
      Taro.showTabBar()
    },200)
  } 

  // 下拉刷新
  Taro.usePullDownRefresh((res) => {
    console.log('下拉刷新')
    offList.value = []
    pageNo = 0
    totalPages = 1
    isNoData = false
    freshList()
    Taro.stopPullDownRefresh()
  })

  // 上拉触底
  Taro.useReachBottom((res) => {
    console.log('触底拉', isNoMore.value)
    isNoMore.value = false
    freshList()
  })

  // onBeforeMount(() => {
  //   let params = Taro.getCurrentInstance().router.params
  //   if (params.from === 'linkwifi') {
      
  //   }

  // })

  // 页面挂载
  onMounted(() => {
    getDeviceList()
    console.log('onMounted')
  })

  Taro.useUnload(() => {
    // Taro.removeStorageSync('lastConnectedDevice');
  })

  // 页面显示时加载页面
  Taro.useDidShow(() => {

    const conncetDivice = Taro.getStorageSync('conncetDivice')
    const isDelDeivce = Taro.getStorageSync('isDelDeivce');
    const isAddDeivce = Taro.getStorageSync('isAddDeivce');
    console.log('isDelDeivce:', isDelDeivce)
    console.log('isAddDeivce:', isAddDeivce)

    // 如果isAddDeivce为真，说明添加过设备，需要更新作品
    if (isAddDeivce) {
      // currentPen.value = []
      deviceId = ''
      isNoData = false
      isSlide.value = false
      Taro.showTabBar()
      getDeviceList(() => {
        Taro.removeStorage({key: 'isAddDeivce'});
      })
    }

    // 如果isDelDeivce为真，说明删除过设备，需要更新作品
    if (isDelDeivce) {
      // currentPen.value = []
      isSlide.value = false
      isNoData = false
      // currentInListIndex.value = 0
      Taro.showTabBar()
      penList.value = []
      getDeviceList(() => {
        Taro.removeStorage({key: 'isDelDeivce'});
      })
    }

  })

  // 获取笔的列表
  function refreshDiviceList() {
    requset('/mini-program/device/list',{
      method: 'post',
      data: {
        userId,
        userToken
      }
    }).then((res)=>{
      const row = res.data.rows
      if (row.length) {
        penList.value = row
      }
    })
  }

  //------------------------------- 获取设备列表 --------------------------------------

  function getDeviceList(fn) {
    requset('/mini-program/device/list',{
      method: 'post',
      data: {
        userId,
        userToken
      }
    }).then(res => {
      // console.log('row:::::',res)
      const row = res.data.rows
      if (row.length) {
        isBind.value = true           // 绑定显示笔
        let prevPageDivce = {}

        console.log('deviceId:', deviceId)

        if (deviceId) {
          prevPageDivce = row.filter(item => item.deviceId === deviceId);
          let selectedPen = {}

          if ( prevPageDivce.length ){
            // 如果匹配出设备
            selectedPen = prevPageDivce[0]
          } else{
            // 如果没有匹配出设备说明此设备已被删除， 默认第一支笔
            offList.value = []
            pageNo = 0
            totalPages = 1
            isNoData = false
            selectedPen = row[0]
          }
          currentPen.value = [selectedPen]
          chooseInfo = selectedPen;             // 设置 chooseInfo 为选中的笔
          deviceId = selectedPen.deviceId;       // 更新 deviceId
        } else {
          const firstPen = row[0];              // 默认选择列表中的第一支笔
          currentPen.value = [firstPen]         // 将第一支笔添加到 currentPen       
          deviceId = firstPen.deviceId;          // 存储第一支笔的 deviceId
          chooseInfo = firstPen;                 // 设置 chooseInfo 为第一支笔
        }
        // 蓝牙检测出的id
        penList.value = row
        console.log('刷新设备列表后加载当前设备的作品：isNoData', isNoData)
        freshList()         // 刷新笔的作品列表
        if(fn) {
          fn()
        }
      } else {
        // 如果没有设备
        freshList(1)
        isBind.value = false  
        isHaveOffering.value = false
      }
    })
  }

  // ------------------------------   获取设备的作品   ----------------------------------------
  function freshList(type) {
    if( isNoData ) {
      isNoMore.value = true  
      return false
    }
    if( isLoading.value ) return false
    isLoading.value = true
    pageNo++
    requset('/mini-program/device/work/list', {
      method: 'post',
      data: {
        deviceId:type?deviceId:'',
        userId,
        userToken,
        pageNo:pageNo,
        pageSize
      }
    }).then(res => {
      // console.log('设备作品列表：', res)
      isLoading.value = false
      const data = res.data.rows
      total = res.data.total
      totalPages = Math.ceil( total / pageSize);

      if( data.length ) {
        // console.log(data.length)
        for( let i=0; i<data.length; i++ ) {
          let json = {}
          let imgUrl = JSON.parse(data[i].detail).url
          if(imgUrl.includes('http') || imgUrl.includes('https')) {
            json.url = imgUrl
          }else{
            json.url = config.baseUrl + imgUrl
          }
          offList.value.push(json)
        }
        isHaveOffering.value = true
        if ( pageNo == totalPages ) {
            isNoMore.value = true
        }
      } else { 
        isNoData = true
      }
    }).catch(err => {
      isLoading.value = false;
      console.error("分页请求失败", err);
    })
  }

  const clickDownLoad = async () => {
  try {
    Taro.showLoading({
      title: '下载中...',
      mask: true
    });

    // 先检查是否授权保存相册
    Taro.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          // 如果没有授权，弹出授权提示框
          Taro.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: () => {
              if (res.authSetting['scope.writePhotosAlbum'] === undefined) {
                Taro.authorize({
                  scope: 'scope.writePhotosAlbum',
                  success () {
                    executeDownload();
                  }
                })
              }else if (res.authSetting['scope.writePhotosAlbum'] === false) {
                Taro.openSetting({
                  success(settingData) {
                    if (settingData.authSetting['scope.writePhotosAlbum']) {
                      Taro.showToast({
                        title: '获取权限成功',
                        icon: 'none'
                      });
                      // 重新执行下载操作
                      executeDownload();
                    } else {
                      Taro.showToast({
                        title: '获取权限失败',
                        icon: 'none'
                      });
                    }
                  }
                });
              }
            }
          });
        } else {
          // 如果已经授权，执行下载操作
          executeDownload();
        }
      }
    });
  } catch (err) {
    console.log(err);
    Taro.hideLoading();
    Taro.showToast({
      title: '下载失败',
      icon: 'none'
    });
  }
};

// 执行图片下载及保存 
// https://tc-nj-brush-od-pub-1324023246.cos.ap-nanjing.myqcloud.com/upload/2024-11-20/F6010A0A000011/fec5784a-d07a-4fc7-8dab-2ef6f95879df/1732064985057/works_1.jpg
const executeDownload = () => {
  console.log('executeDownloa - imageUrl.value:', imageUrl.value)
  Taro.downloadFile({
    url: imageUrl.value, // 图片 URL
    success: function (res) {
      Taro.getImageInfo({
        src: res.tempFilePath,
        success: function (infoRes) {
          let path = infoRes.path;
          Taro.saveImageToPhotosAlbum({
            filePath: path,
            success() {
              Taro.hideLoading();
              Taro.showToast({
                title: '保存成功',
                icon: 'none',
                duration: 3000
              });
            },
            fail(err) {
              Taro.hideLoading();
              if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
                Taro.showToast({
                  title: '保存失败，请重新下载',
                  icon: 'none',
                  duration: 3000
                });
                return;
              }
              if (err.errMsg.includes('saveImageToPhotosAlbum:fail')) {
                Taro.showToast({
                  title: '未知错误，请稍后再试',
                  icon: 'none',
                  duration: 3000
                });
              } else {
                Taro.showToast({
                  title: '需要您授权保存相册',
                  icon: 'none',
                  duration: 3000
                });
              }
            }
          });
        },
        fail(err) {
          Taro.hideLoading();
          Taro.showToast({
            title: '获取图片信息失败',
            icon: 'none'
          });
        }
      });
      // if (res.statusCode === 200) {
        
      // } else {
      //   Taro.showToast({
      //     title: '图片下载失败',
      //     icon: 'none'
      //   });
      // }
    },
    fail(err) {
      Taro.hideLoading();
      Taro.showToast({
        title: '图片下载失败',
        icon: 'none'
      });
    }
  });
};


  // 下载图片方法
  // const clickDownLoad = async () => {
  //   try {
  //     Taro.showLoading({
  //       title: '下载中...',
  //       mask: true
  //     })
  //     // let res = await downPushData()
  //     // if (res.errCode != 0) throw res;

  //     Taro.getImageInfo({
  //       src: imageUrl.value,
  //       success: function(res) {
  //         let path = res.path
  //         Taro.saveImageToPhotosAlbum({
  //           filePath: path,
  //           success(res) {
  //             Taro.hideLoading();
  //             Taro.showToast({
  //               title: '保存成功',
  //               icon: 'none',
  //               duration: 3000
  //             })
  //           },
  //           fail(err) {
  //             Taro.hideLoading()
  //             if( err.errMsg === 'saveImageToPhotosAlbum:fail cancel' ) {
  //               Taro.showToast({
  //                 title: '保存失败，请重新下载',
  //                 icon: 'none',
  //                 duration: 3000
  //               })
  //               return
  //             }
  //             Taro.showModal({
  //               title: '提示',
  //               content: '需要您授权保存相册',
  //               showCancel: false,
  //               success: res => {
  //                 if(res.confirm) {
  //                   Taro.openSetting({
  //                     success(settingdata) {
  //                       if(settingdata.authSetting['scope.writePhotosAlbum']) {
  //                         Taro.showToast({
  //                           title: '获取权限成功',
  //                           icon: 'none'
  //                         })
  //                       } else {
  //                         Taro.showToast({
  //                           title: '获取权限失败',
  //                           icon: 'none'
  //                         })
  //                       }
  //                     }
  //                   })
  //                 }
  //               }
  //             })
  //           }
  //         })
  //       }
  //     })

  //   } catch (err) {
  //     console.log(err)
  //     Taro.hideLoading()
  //   }
  // }

  function checkPermissions() {


  }

  function saveImg() {

  }

</script>
  
<style>
/* 字画详情start */

.picture_detail{
  width: 100%;
  height: 100%;
  background-color: #000;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 101;
}

/* 字画详情over */

.offe_item {
  margin-bottom: 20px;
}

.offe_item:nth-child(odd) {
  width: 320px;
  height: 320px;
  border-radius: 20px;
  overflow: hidden;
  background-color: #FFF;
  position: relative;
  float: left;
}

.offe_item:nth-child(even) {
  width: 320px;
  height: 320px;
  border-radius: 20px;
  overflow: hidden;
  background-color: #FFF;
  position: relative;
  float: right;
}

.offe_item cover-img {
  width: 100%;
  height: 100%;
}

.offe_item .cheack_detal {
  width: 100%;
  height: 72px;
  line-height: 72px;
  text-align: center;
  color: #fff;
  background-color: rgba(0,0,0,.5);
  backdrop-filter: blur(10px);
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 1;
}


.offering_list {
  width: 100%;
  /* min-height: 800px; */
  margin: 20px auto 0 auto;
  /* overflow: scroll; */
  /* background-color: #FFF; */
  overflow: hidden;
}

.pen_content{
  width: 90%;
  margin: 40px auto 0 auto;
}

.pen_item {
  width: 100%;
  height: 200px;
  padding: 40px 32px;
  box-sizing: border-box;
  border-radius: 20px;
  background-color: #FFF;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  
}
.pen_text {
  width: 400px;
  font-family: 'siyuan',sans-serif;
  font-size: 40px;
  font-weight: bold;
  text-align: left;
  display: inline-block;
}

.connect_btn {
  width: 148px;
  height: 80px;
  line-height: 80px;
  font-size: 30px;
  color: #FFF;
  background-color: #956F31;
  border-radius: 50px;
  display: inline-block;
  border: 0
}

.no_offering_content {
  width: 100%;
  height: 800px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 1;
}

.no_offering {
  width: 216px;
  height: 228px;
}

.no_offering_text {
  color: #816747;
  margin-top: 20px;
}

.refresh {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  color: #C3B3A0;
}

.slide_view {
  width: 100%;
  background-color: #F7F3E8;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  position: fixed;
  bottom:-1800px;
  transition: all .5s;
  z-index: 10000;
  padding: 50px 0;
  box-sizing: border-box;
}

.close_btn {
  width: 32px;
  height: 32px;
  position: absolute;
  right: 32px;
  top: 32px;
  background: url('../../images/icon_close.png') no-repeat;
  background-size: 100%;
}

.slide_title {
  width: 100%;
  text-align: center;
  display: inline-block;
  font-family: 'siyuan',sans-serif;
  font-size: 40px;
}

.choose_list {
  max-height: 900px;
  overflow: scroll;
  width: 90%;
  margin: 50px auto 20px auto; 
}

.slide_bottom{
  width: 100%;
  height: 156px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-around;
}

.slide_bottom button {
  width: 320px;
  height: 112px;
  line-height: 112px;
  font-size: 40px;
  border: none;
  border-radius: 100px;
  border: 0;
}

.bind_new_device[plain] {
  color: #956F31;
  background-color: #FFF;
  border: none
}

.slide_bottom button:nth-child(1) {
  color: #956F31;
  background-color: #FFF;
  border: 1px solid #FFF;
}

.slide_bottom button:nth-child(2) {
  color: #FFF;
  background-color: #956F31;
}

@keyframes rotateLoading {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.loading_box {
  width: 100%;
  height: 50px;
  margin-top: 20px;
  padding-bottom: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
.icon_loading {
  width: 48px;
  height: 48px;
  animation: rotateLoading 1s linear infinite;
  margin-right: 10px;
}

.no_more_box{
  width: 100%;
  height: 50px;
  text-align: center;
  color: #C3B3A0;
}

.preview-container {
  position: fixed;
  top: 0;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh; /* 让容器占满整个视口 */
  background-color: #000; 
}

.preview-container::before, .preview-container::after{
  content: '';
  width: 100%;
  height: 280px;
  background: linear-gradient(to bottom, rgba(0,0,0,.5) 0%,rgba(0,0,0,0) 100%);
  position: absolute;
  z-index: 10;
}

.preview-container::before{
  top: 0;
  left: 0;
}

.preview-container::after{
  bottom: 0;
  left: 0;
  transform: rotate(180deg);
}

.image-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%; /* 容器宽度 */
  max-height: 80%; /* 最大高度控制 */
  overflow: hidden; /* 防止溢出 */
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
}
.download-button {
  width: 90%;
  height: 112px;
  background-color: #FFFBF2; /* 按钮颜色 */
  color: #3B2122; /* 字体颜色 */
  border: none;
  border-radius: 100px;
  position: absolute;
  bottom: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  z-index: 20;
}

.download_icon{
  width: 48px;
  height: 48px;
}

.rotate180 {
  transform: rotate(180);
}



</style>